﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;

namespace DailyPhoto.Common
{
    public static class Application
    {
        private static string configpath;
        static Application()
        {
            try
            {
                if (Assembly.GetEntryAssembly() == null)
                {
                    Config = new JObject();
                    return;
                }

                configpath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\" +
                    Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location) + ".jconfig";

                var st =
                    new StreamReader(configpath);

                try
                {
                    Config = JObject.Parse("{" + st.ReadToEnd() + "}");
                }
                finally
                {
                    st.Close();
                }

            }
            catch (FileNotFoundException)
            {
                Config = new JObject();
            }
            catch (Exception e)
            {
                throw new DailyphotoException("Failed to parse application config!", e);
            }
        }

        public static JObject GetConfig()
        {
            return Config;
        }

        public static dynamic Config
        {
            get;
            set;
        }


        public static void SaveConfig()
        {
            try
            {


                string data = Config.ToString();
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(configpath))
                {

                    file.WriteLine(data);
                }

            }
            catch (Exception e)
            {
                throw new DailyphotoException(
                    string.Format("Failed to save configuration file {0}", e.ToString()));
            }
        }

        public static void LoadConfig(string cfgfile)
        {
            try
            {
                using (var sr = new StreamReader(cfgfile))
                {
                    try
                    {
                        Config = JObject.Parse("{" + sr.ReadToEnd() + "}");
                    }
                    finally
                    {
                    }
                }

            }
            catch (Exception e)
            {
                throw new DailyphotoException(
                    string.Format("Failed to load configuration file {0}", e.ToString()));
            }
        }
    }
}
